package com.feihong.yw189.activity.kaika;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SDCardUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.http.FileUploader;
import com.feihong.yw189.http.FileUploaderCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.Kaika.UpLoadPicModel;
import com.feihong.yw189.utils.PhotoUtils;


import java.io.File;
import java.util.concurrent.CountDownLatch;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 用户照片上传   主页
 */

@RuntimePermissions
public class KaikaUploadPicActivity extends BaseActivity implements View.OnClickListener {
    public static final int KAIKA_UP_USER_IMG_REQUEST = 13;

    @BindView(R.id.rl_goback)
    RelativeLayout ivBack;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.iv_zhengmian)
    ImageView ivZhengMian;
    @BindView(R.id.iv_beimian)
    ImageView ivBeiMian;
    @BindView(R.id.iv_shouchi)
    ImageView ivShouChi;
    @BindView(R.id.iv_gongan)
    ImageView ivGongAn;
    @BindView(R.id.ll_shouli)
    LinearLayout llshouli;

    private MyUsualyDialog mydialog;

    public static final String ZHENGMIAN_URL_REP = "ZHENGMIANURLREP";
    public static final String BEIMIAN_URL_REP = "BEIMIANURLREP";
    public static final String SHOUCHI_URL_REP = "SHOUCHIURLREP";
    public static final String GON_GAN_URL_REP = "GONGANURLREP";

    public static final String ZHENGMIAN_URL = "ZHENGMIANURL";
    public static final String BEIMIAN_URL = "BEIMIANURL";
    public static final String SHOUCHI_URL = "SHOUCHIURL";
    public static final String GON_GAN_URL = "GONGANURL";

    private File fileUri = null;
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    BaseBottomDialog dialog = null;
    /**
     * 0拍照 1相册
     */
    private int photoType = 0;
    /**
     * 正面   1背面   2手持   3公安
     */
    private int gettype = 0;
    File zhengMianFile, beiMianFile, shouChiFile, gongAnFile;

    /**
     * 是否需要上传号码等级协议图片
     */
    public static final String IS_NEED_UPLOAD_PROTOCOL_KEY = "IS_NEED_PROTOCOL_KEY";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.useruploadpic_activity);
        ButterKnife.bind(this);

        initView();
    }

    @Override
    public void setTheme() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    private void initView() {
        txtPagetitle.setText("用户照片上传");
        ivLin.setVisibility(View.GONE);
        llshouli.setVisibility(View.GONE);

        mydialog = new MyUsualyDialog(KaikaUploadPicActivity.this, R.layout.wait_item);
        mydialog.setCanceledOnTouchOutside(true);
        mydialog.setCancelable(false);
    }

    private void takePhoto(int id) {
        try {
            String sdCardPath = SDCardUtils.getSDCardPathByEnvironment();
            if (TextUtils.isEmpty(sdCardPath)) {
                showToast("SD卡不可用，请检查权限是否给全！");
                return;
            }
            File dirPath = new File(sdCardPath + "/YW189/");
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File filePath = null;
            switch (id) {
                case R.id.iv_zhengmian:
                    //正面照片
                    gettype = 0;
                    filePath = new File(dirPath.getAbsolutePath() + "/zhengmian.jpg");
                    break;
                case R.id.iv_beimian:
                    gettype = 1;
                    filePath = new File(dirPath.getAbsolutePath() + "/beimian.jpg");
                    break;
                case R.id.iv_shouchi:
                    gettype = 2;
                    filePath = new File(dirPath.getAbsolutePath() + "/shouchi.jpg");
                    break;
                case R.id.iv_gongan:
                    gettype = 3;
                    filePath = new File(dirPath.getAbsolutePath() + "/gongan.jpg");
                    break;
                default:
                    break;
            }
            fileUri = filePath;
            photoType = 0;
            KaikaUploadPicActivityPermissionsDispatcher.NeedsCameraPermissionWithCheck(this);
        } catch (Exception ex) {
            ex.printStackTrace();
            showToast("出错：无法创建制定的文件夹，请重试！");
        }
    }

    @Override
    @OnClick({R.id.rl_goback, R.id.iv_zhengmian, R.id.iv_beimian, R.id.iv_shouchi,
            R.id.iv_gongan, R.id.upLoadpic_submit_btn
    })
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_goback:
                finish();
                break;
            case R.id.iv_zhengmian:
                //正面照片
                takePhoto(v.getId());
                break;
            case R.id.iv_beimian:
                //背面照片

                takePhoto(v.getId());
                break;
            case R.id.iv_shouchi:
                //手持照片

                takePhoto(v.getId());

                break;
            case R.id.iv_gongan:
                //公安对比照   相册或者拍照
                takePhoto(v.getId());
                break;
            case R.id.upLoadpic_submit_btn:
                submit1();

                break;
            case R.id.user_take_photo:
                //拍照
                photoType = 0;
                KaikaUploadPicActivityPermissionsDispatcher.NeedsCameraPermissionWithCheck(this);
                dialog.dismiss();
                break;
            case R.id.user_select_from_lib:
                //相册
                photoType = 1;
                KaikaUploadPicActivityPermissionsDispatcher.NeedsCameraPermissionWithCheck(this);
                dialog.dismiss();
                break;
            case R.id.user_photo_cancel:
                //取消
                dialog.dismiss();
                break;
            default:
                break;
        }
    }

    /**
     * 拍照相册选择dialog
     */

    private void dialogChoose() {
        dialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.activity_my_photo_edit)
                .setDimAmount(0.5f)
                // Dialog window 背景色深度 范围：0 到 1，默认是0.2f
                .setCancelOutside(false)
                // 点击外部区域是否关闭，默认true
                .setTag("BottomDialog")
                // 设置DialogFragment的tag
                .setViewListener(v -> dialogClick(v))
                .show();
    }

    private void dialogClick(View v) {
        v.findViewById(R.id.user_take_photo).setOnClickListener(this);
        v.findViewById(R.id.user_select_from_lib).setOnClickListener(this);
        v.findViewById(R.id.user_photo_cancel).setOnClickListener(this);
    }

    /***
     * 开始打开照相机
     */
    private void openCamera() {
        PhotoUtils.takePicture(this, fileUri, CODE_CAMERA_REQUEST);
    }


    private void cameraRequestOK() {
        //裁剪结果 -> 鲁班压缩
        if (fileUri != null) {
            switch (gettype) {
                case 0:
                    zhengMianFile = fileUri;
                    Glide.with(this).load(zhengMianFile).apply(new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)).into(ivZhengMian);
                    break;
                case 1:
                    beiMianFile = fileUri;
                    Glide.with(this).load(beiMianFile).apply(new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)).into(ivBeiMian);
                    break;
                case 2:
                    shouChiFile = fileUri;
                    Glide.with(this).load(shouChiFile).apply(new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)).into(ivShouChi);
                    break;
                case 3:
                    gongAnFile = fileUri;
                    Glide.with(this).load(gongAnFile).apply(new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE)).into(ivGongAn);
                    break;
                default:
                    break;
            }
        }
    }


    private String zhengMianUrlRep = null;
    private String zhengMianUrl = null;
    private String beiMianUrlRep = null;
    private String beiMianUrl = null;
    private String shouChiUrl_rep = null;
    private String shouChiUrl = null;

    /***
     * 上传图片 第一步  上传正面图片
     */
    private void submit1() {
        if (zhengMianFile == null || !zhengMianFile.exists()) {
            showToast("请上传身份证正面照");
            return;
        }
        if (beiMianFile == null || !beiMianFile.exists()) {
            showToast("请上传身份证背面照");
            return;
        }
        if (shouChiFile == null || !shouChiFile.exists()) {
            showToast("请上传手持身份证照");
            return;
        }
        mydialog.setCancelable(false);
        mydialog.show();
        mydialog.setWarningTxt(R.id.progress_layout_warning_tv, "图片处理中");
        FileUploader fileUploader = new FileUploader(this);
        try {
            fileUploader.uploadFile(1001, zhengMianFile.getAbsolutePath(), new FileUploaderCallBack() {
                @Override
                public void success(int req, String path, UpLoadPicModel model, String result) {
                    if (activityIsDestory()) {
                        return;
                    }
                    zhengMianUrl = model.getData().getUrl();
                    zhengMianUrlRep = model.getData().getUrl_rep();
                    if (TextUtils.isEmpty(zhengMianUrl) || TextUtils.isEmpty(zhengMianUrlRep)) {
                        if (mydialog != null && mydialog.isShowing()) {
                            mydialog.dismiss();
                        }
                        showToast("上传身份证正面照失败，请重新上传");
                    } else {
                        submit2();
                    }
                }

                @Override
                public void error(int req, String path, String error) {
                    if (activityIsDestory()) {
                        return;
                    }
                    if (mydialog != null && mydialog.isShowing()) {
                        mydialog.dismiss();
                    }
                    showToast(error);
                }
            });
        } catch (Exception ex) {
            if (mydialog != null && mydialog.isShowing()) {
                mydialog.dismiss();
            }
            showToast("处理失败，请重试!错误代码:1001");
        }
    }

    /***
     * 上传背面图
     */
    private void submit2() {
        FileUploader fileUploader = new FileUploader(this);
        try {
            fileUploader.uploadFile(1002, beiMianFile.getAbsolutePath(), new FileUploaderCallBack() {
                @Override
                public void success(int req, String path, UpLoadPicModel model, String result) {
                    if (activityIsDestory()) {
                        return;
                    }
                    beiMianUrl = model.getData().getUrl();
                    beiMianUrlRep = model.getData().getUrl_rep();
                    if (TextUtils.isEmpty(beiMianUrl) || TextUtils.isEmpty(beiMianUrlRep)) {
                        if (mydialog != null && mydialog.isShowing()) {
                            mydialog.dismiss();
                        }
                        showToast("上传身份证背面照片失败，请重新上传");
                    } else {
                        submit3();
                    }
                }

                @Override
                public void error(int req, String path, String error) {
                    if (activityIsDestory()) {
                        return;
                    }
                    if (mydialog != null && mydialog.isShowing()) {
                        mydialog.dismiss();
                    }
                    showToast(error);
                }
            });
        } catch (Exception ex) {
            if (mydialog != null && mydialog.isShowing()) {
                mydialog.dismiss();
            }
            showToast("处理失败，请重试!错误代码:1002");
        }
    }

    /***
     * 上传背面图
     */
    private void submit3() {
        FileUploader fileUploader = new FileUploader(this);
        try {
            fileUploader.uploadFile(1003, shouChiFile.getAbsolutePath(), new FileUploaderCallBack() {
                @Override
                public void success(int req, String path, UpLoadPicModel model, String result) {
                    if (activityIsDestory()) {
                        return;
                    }
                    shouChiUrl = model.getData().getUrl();
                    shouChiUrl_rep = model.getData().getUrl_rep();
                    if (TextUtils.isEmpty(shouChiUrl) || TextUtils.isEmpty(shouChiUrl_rep)) {
                        if (mydialog != null && mydialog.isShowing()) {
                            mydialog.dismiss();
                        }
                        showToast("上传手持证件照失败，请重新上传");
                        return;
                    }
                    if (mydialog != null && mydialog.isShowing()) {
                        mydialog.dismiss();
                    }
                    zhengMianFile.delete();
                    beiMianFile.delete();
                    shouChiFile.delete();
                    Intent intent = new Intent();
                    intent.putExtra(ZHENGMIAN_URL, zhengMianUrl);
                    intent.putExtra(BEIMIAN_URL, beiMianUrl);
                    intent.putExtra(SHOUCHI_URL, shouChiUrl);
                    intent.putExtra(ZHENGMIAN_URL_REP, zhengMianUrlRep);
                    intent.putExtra(BEIMIAN_URL_REP, beiMianUrlRep);
                    intent.putExtra(SHOUCHI_URL_REP, shouChiUrl_rep);
                    setResult(RESULT_OK, intent);
                    finish();
                }

                @Override
                public void error(int req, String path, String error) {
                    if (activityIsDestory()) {
                        return;
                    }
                    mydialog.dismiss();
                    showToast(error);
                }
            });
        } catch (Exception ex) {
            if (mydialog != null && mydialog.isShowing()) {
                mydialog.dismiss();
            }
            showToast("处理失败，请重试!");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(resultCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            cameraRequestOK();
        }
    }


    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void NeedsCameraPermission() {
        switch (photoType) {
            case 0:
                openCamera();
                break;
            case 1:
                PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                break;
            default:
                break;
        }
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void ShowCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获取相机权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void Denied() {
        showErrorDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void AskCamera() {
        showErrorDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        KaikaUploadPicActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onDestroy() {
        if (mydialog != null && mydialog.isShowing()) {
            mydialog.dismiss();
        }
        super.onDestroy();
    }
}
